<template>
  <div class="container">
    <!-- <div class="blockTitle">
        账号设置  
    </div>  -->
    <topTitle :titleText="titleText"></topTitle>
    <div class="mainCon">
      <el-row>
        <div class="fl">
          <div class="updateItem">账号密码</div>
          <div class="itemBox">
            <span class="itemTitle">账号名：</span>
            <span class="itemValue">{{ userName }}</span>
          </div>
        </div>
        <div class="fr">
          <el-button
            type="primary"
            class="miniButColor"
            size="mini"
            round
            @click="updatePassword()"
            ><i class="iconfont iconbianji"></i>修改</el-button
          >
        </div>
      </el-row>
      <el-collapse-transition>
        <div v-show="updatePass">
          <div class="transition-box">
            <el-divider>修改账号密码</el-divider>
            <el-form
              :model="passwordForm"
              :rules="passwordRule"
              class="passwordForm"
              ref="passwordForm"
              label-width="120px"
              aria-autocomplete="false"
            >
              <el-form-item label="当前账号：" prop="name">
                <el-input type="text" v-model.trim="userAndName" disabled>{{
                  userAndName
                }}</el-input>
              </el-form-item>
              <el-form-item label="旧密码：" prop="oldPass">
                <el-input
                  type="password"
                  v-model.trim="passwordForm.oldPass"
                  placeholder="输入旧密码"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item label="新密码：" prop="newPass">
                <el-input
                  type="password"
                  v-model.trim="passwordForm.newPass"
                  show-password
                  clearable
                  placeholder="输入新密码"
                ></el-input>
              </el-form-item>
              <el-form-item label="确认新密码：" prop="checkPass">
                <el-input
                  type="password"
                  v-model.trim="passwordForm.checkPass"
                  show-password
                  clearable
                  placeholder="输入新密码"
                ></el-input>
              </el-form-item>
            </el-form>
            <div class="btnBox">
              <el-button
                type="primary"
                size="medium"
                class="commonBut saveBtn"
                @click="submitPassForm()"
                :loading="canSubmit"
                >保存修改</el-button
              >
              <el-button
                size="medium"
                class="cancelBtn"
                @click="cancelSubmit('passwordForm')"
                >取消</el-button
              >
            </div>
          </div>
        </div>
      </el-collapse-transition>
      <el-divider></el-divider>
      <el-row>
        <div class="fl">
          <div class="updateItem backYellow">密保手机</div>
          <div class="itemBox">
            <span class="itemTitle">已绑定手机：</span>
            <span class="itemValue"
              >{{ phone }}，密保手机号可用于修改和找回账号密码</span
            >
          </div>
        </div>
        <div class="fr">
          <el-button
            type="primary"
            class="miniButColor"
            size="mini"
            round
            @click="updateTelEvent()"
            ><i class="iconfont iconbianji"></i>修改</el-button
          >
        </div>
      </el-row>
      <el-collapse-transition>
        <div v-show="updateTel">
          <div class="transition-box">
            <el-divider>修改密保手机号</el-divider>
            <el-form
              :model="telForm"
              :rules="telRule"
              class="telForm"
              ref="telForm"
              label-width="120px"
              aria-autocomplete="false"
            >
              <el-form-item label="当前账号：" prop="name">
                <el-input
                  type="text"
                  v-model.trim="userAndName"
                  disabled
                ></el-input>
              </el-form-item>
              <el-form-item label="密保手机号：" prop="tel">
                <el-input type="text" v-model.trim="phone" disabled></el-input>
              </el-form-item>
              <el-form-item label="验证码：" prop="vscode" class="vscodeInput">
                <el-input
                  type="text"
                  v-model.trim="telForm.vscode"
                  placeholder="输入验证码"
                  clearable
                ></el-input>
                <el-button
                  class="getCode"
                  type="primary"
                  plain
                  size="medium"
                  round
                  v-show="!isCount"
                  @click="getVscode()"
                  :disabled="canClick"
                  >获取验证码</el-button
                >
                <el-button
                  type="info"
                  plain
                  size="medium"
                  round
                  v-show="isCount"
                  disabled
                  >{{ countDownTime }}s后重新获取</el-button
                >
              </el-form-item>
              <el-form-item label="新手机号：" prop="newTel">
                <el-input
                  type="text"
                  v-model.trim="telForm.newTel"
                  placeholder="输入新密保手机号"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item label="确认新手机号：" prop="newTelToo">
                <el-input
                  type="text"
                  v-model.trim="telForm.newTelToo"
                  placeholder="再次输入新密保手机号"
                  clearable
                ></el-input>
              </el-form-item>
            </el-form>
            <div class="btnBox">
              <el-button
                type="primary"
                class="commonBut saveBtn"
                @click="submitTelForm()"
                :loading="canUpdate"
                >保存修改</el-button
              >
              <el-button class="commonBut" @click="cancelSubmit('telForm')"
                >取消</el-button
              >
            </div>
          </div>
        </div>
      </el-collapse-transition>
    </div>
  </div>
</template>

<script>
export default {
  name: 'setPhone',

  data() {
    var validateOldPass = (rule, value, callback) => {
      value = value.replace(/\s+/g, '')
      if (value === '') {
        callback(new Error('旧密码不能为空'))
      } else {
        var data = {}
        var url = ''
        if (localStorage.getItem('loginType') == 'DT') {
          url = 'api-m/inputUser/base/v1/validPassword'
          data = {
            id: this.$store.state.userId, //----用户id
            password: value,
          }
        } else {
          url = 'api-u/validpassword'
          data = {
            password: value,
          }
        }
        this.axios({
          method: 'post',
          url,
          data,
        }).then(
          (res) => {
            if (!res.data.hasError) {
              callback()
            } else {
              callback(new Error(res.data.errorMsg))
            }
          },
          (response) => {
            callback(new Error('验证旧密码失败'))
          }
        )
      }
    }
    //验证密码
    var validatePass1 = (rule, value, callback) => {
      value = value.replace(/\s+/g, '')
      if (value === '') {
        callback(new Error('新密码不能为空'))
      } else {
        if (value.length < 6 || value.length > 18) {
          callback('密码长度应为6-18位')
        } else {
          var reg = /[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]a-zA-Z0-9]{6,18}$/
          if (!reg.test(value)) {
            callback('密码仅支持数字、字母、英文符号，不支持空格')
          } else {
            if (this.passwordForm.checkPass !== '') {
              this.$refs.passwordForm.validateField('checkPass')
            }
            callback()
          }
        }
      }
    }
    var validatePass2 = (rule, value, callback) => {
      value = value.replace(/\s+/g, '')
      if (value === '') {
        callback(new Error('新密码不能为空'))
      } else {
        if (value != this.passwordForm.newPass) {
          callback(new Error('两次密码输入不一致'))
        }
        callback()
      }
    }
    //验证手机号
    var validateTel1 = (rule, value, callback) => {
      value = value.replace(/\s+/g, '')
      if (value === '') {
        callback(new Error('新手机号不能为空'))
      } else {
        var regTel = /^1[3456789]\d{9}$/
        if (!regTel.test(value)) {
          callback(new Error('手机号码格式不正确'))
        } else {
          if (this.telForm.newTelToo !== '') {
            this.$refs.telForm.validateField('newTelToo')
            callback()
          }
        }
      }
    }
    var validateTel2 = (rule, value, callback) => {
      value = value.replace(/\s+/g, '')
      if (value === '') {
        callback(new Error('新手机号不能为空'))
      } else {
        var regTel = /^1[3456789]\d{9}$/
        if (!regTel.test(value)) {
          callback(new Error('手机号码格式不正确'))
        } else {
          if (value != this.telForm.newTel) {
            callback(new Error('两次手机号输入不一致'))
          }
          callback()
        }
      }
    }
    //验证短信验证码
    var validateVsode = (rule, value, callback) => {
      value = value.replace(/\s+/g, '')
      if (value === '') {
        callback(new Error('验证码不能为空'))
      } else {
        var url = 'api-bs/message/base/checkvc'
        var data = {
          tel: this.telphone,
          vc: this.telForm.vscode,
        }
        this.axios({
          method: 'post',
          url: url,
          data: data,
        }).then(
          (res) => {
            if (!res.data.hasError) {
              callback()
            } else {
              callback(new Error(res.data.errorMsg))
            }
          },
          (response) => {
            callback(new Error('验证失败'))
          }
        )
      }
    }
    return {
      titleText: '账号设置',
      type: '', //修改手机号还是密码
      showQy: false, //是否展示企业设置
      loginType: 'QY', //默认登录类型
      userName: '', //账号名
      companyName: '', //公司名
      userAndName: '',
      telphone: '', //未脱敏旧手机号
      phone: '', //手机号
      updatePass: false,
      updateTel: false,
      canClick: false, //不可以点击获取验证码
      isCount: false, //短信验证码
      countDownTime: 60, //倒计时
      canSubmit: false, //是否可以提交
      canUpdate: false, //是否可以提交修改手机号
      passwordRule: {
        oldPass: [
          { required: true, validator: validateOldPass, trigger: 'blur' },
        ],
        newPass: [
          { required: true, validator: validatePass1, trigger: 'blur' },
        ],
        checkPass: [
          { required: true, validator: validatePass2, trigger: 'blur' },
        ],
      },
      passwordForm: {
        oldPass: '',
        newPass: '',
        checkPass: '',
      },
      telRule: {
        vscode: [{ required: true, validator: validateVsode, trigger: 'blur' }],
        newTel: [{ required: true, validator: validateTel1, trigger: 'blur' }],
        newTelToo: [
          { required: true, validator: validateTel2, trigger: 'blur' },
        ],
      },
      telForm: {
        tel: '',
        vscode: '',
        newTel: '',
        newTelToo: '',
      },
      auth_timetimer: null,
    }
  },
  created() {
    //判断用户类型
    this.loginType = localStorage.getItem('loginType')
    if (this.loginType === 'QY') {
      this.showQy = true
    } else {
      this.showQy = false
    }

    this.showForm()

    //获取页面信息
    // this.getInfo();
    //未脱敏手机号
    this.telphone = this.$store.state.userTel
    //脱敏手机号
    if (this.telphone) {
      this.phone =
        this.telphone.substring(0, 3) +
        '****' +
        this.telphone.substring(this.telphone.length - 4)
    }
    this.userAndName = this.$store.state.usernameAndType
  },
  methods: {
    //根据修改类型显示不同的修改表单
    showForm() {
      this.type = this.$route.query.type
      if (this.type === 'tel') {
        this.updatePass = false
        this.updateTel = true
      }
      if (this.type === 'password') {
        this.updatePass = true
        this.updateTel = false
      }
    },
    //修改密码
    updatePassword() {
      this.updatePass = true
      this.updateTel = false
      this.canSubmit = false
      this.$nextTick(function () {
        this.$refs.passwordForm.resetFields()
      })
    },
    //修改手机号
    updateTelEvent() {
      this.updatePass = false
      this.updateTel = true
      this.canUpdate = false
      this.$nextTick(function () {
        this.$refs.telForm.resetFields()
      })
    },
    //获取页面信息
    getInfo() {
      let vm = this
      vm.axios({
        method: 'post',
        url: 'api-u/useraccount',
      })
        .then(
          (res) => {
            if (!res.data.hasError) {
              var data = res.data.result
              vm.userName = data.username
              vm.companyName = data.nickname
              vm.telphone = data.tel
              vm.userAndName = vm.userName + '(' + vm.companyName + ')'
              var tel =
                vm.telphone.substring(0, 3) +
                '****' +
                vm.telphone.substring(vm.telphone.length - 4)
              vm.phone = tel
            }
          },
          (response) => {
            this.$message({
              message: '获取账号信息失败',
              type: 'error',
            })
          }
        )
        .catch((error) => {})
    },
    //发送验证码倒计时
    countDown() {
      let vm = this
      //开启倒计时
      vm.isCount = true
      this.auth_timetimer = setInterval(() => {
        vm.countDownTime--
        if (vm.countDownTime <= 0) {
          vm.isCount = false
          clearInterval(vm.auth_timetimer)
          vm.countDownTime = 60
        }
      }, 1000)
    },
    //发送短信验证码
    getVscode() {
      this.canClick = true
      //验证码倒计时
      let vm = this
      vm.axios({
        method: 'post',
        url: 'api-bs/message/base/sendvc',
        data: {
          tel: vm.telphone,
        },
      })
        .then(
          (res) => {
            vm.canClick = false
            //已发送验证码
            if (!res.data.hasError) {
              this.$message({
                showClose: true,
                message: '验证码已发送至您的旧手机',
                type: 'success',
              })
              //验证码倒计时
              this.countDown()
            } else {
              this.$message({
                message: res.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {
            this.$message({
              message: '发送验证码失败',
              type: 'error',
            })
            vm.canClick = false
          }
        )
        .catch((error) => {
          vm.canClick = false
        })
    },
    //密码修改成功后自动退出该账号并跳转至登录页面；
    logout() {
      var vm = this
      vm.axios({
        method: 'get',
        url:
          'api-u/sys/logout?Authorization=' +
          localStorage.getItem('access_token'),
      })
        .then(
          (res) => {
            //清除token
            localStorage.setItem('access_token', '')
            localStorage.setItem('refresh_token', '')
            localStorage.setItem('userName', '')
            vm.$router.replace('/login/loginNext?type=' + this.loginType)
          },
          (res) => {
            localStorage.setItem('access_token', '')
            localStorage.setItem('refresh_token', '')
            localStorage.setItem('userName', '')
            vm.$router.replace('/login/loginNext?type=' + this.loginType)
          }
        )
        .catch((error) => {})
    },
    //修改密码保存
    submitPassForm() {
      let vm = this
      vm.$refs['passwordForm'].validate((valid) => {
        if (valid) {
          vm.canSubmit = true
          vm.axios({
            method: 'post',
            url: 'api-u/users/editpassword',
            data: {
              password: vm.passwordForm.newPass,
            },
          })
            .then(
              (res) => {
                vm.canSubmit = false
                this.$message({
                  showClose: true,
                  message: '密码修改成功,请重新登录',
                  type: 'success',
                })
                this.logout()
              },
              (response) => {
                this.$message({
                  message: '修改失败',
                  type: 'error',
                })
                vm.canSubmit = false
              }
            )
            .catch((error) => {})
        } else {
          vm.canSubmit = false
          return false
        }
      })
    },
    //提交修改手机号
    submitTelForm() {
      let vm = this
      vm.$refs['telForm'].validate((valid) => {
        if (valid) {
          vm.canUpdate = true
          vm.axios({
            method: 'post',
            url: 'api-u/usertel',
            data: {
              vc: vm.telForm.vscode,
              tel: vm.telphone,
              newTel: vm.telForm.newTel,
            },
          }).then(
            (res) => {
              vm.canUpdate = false
              if (!res.data.hasError) {
                this.$message({
                  showClose: true,
                  message: '手机号修改成功',
                  type: 'success',
                })
                vm.telphone = vm.telForm.newTel
                vm.phone =
                  vm.telphone.substring(0, 3) +
                  '****' +
                  vm.telphone.substring(vm.telphone.length - 4)
                vm.updateTel = false
                //清空表单
                vm.telForm.vscode = ''
                vm.telForm.newTel = ''
                vm.telForm.newTelToo = ''
                vm.getInfo()
                vm.isCount = false
                clearInterval(vm.auth_timetimer)
                vm.auth_timetimer = null
                vm.countDownTime = 60
              } else {
                this.$message({
                  message: res.data.errorMsg,
                  type: 'error',
                })
              }
            },
            (response) => {
              this.$message({
                message: '修改失败',
                type: 'error',
              })
              vm.canUpdate = false
            }
          )
        } else {
          vm.canUpdate = false
        }
      })
    },
    //取消修改
    cancelSubmit(formName) {
      if (formName == 'passwordForm') {
        this.updatePass = false
      } else if (formName == 'telForm') {
        this.updateTel = false
      }
      // 取消
      this.$refs[formName].resetFields()
    },
  },
  destroyed() {
    clearInterval(this.auth_timetimer)
    this.auth_timetimer = null
  },
}
</script>

<style lang="less" scoped>
.container {
  // position: absolute;
  // padding: 24px;
  // top: 106px;
  // bottom: 0px;
  // left: 0px;
  // right: 0px;
  // overflow-y: auto;
  // overflow-x: hidden;
  .blockTitle {
    height: 66px;
    line-height: 46px;
    padding: 10px 24px;
    background-color: #e4ebf1;
    font-size: 18px;
    font-weight: bold;
  }
  .passwordForm,
  .telForm {
    width: 500px;
    margin: 50px auto;
    .vscodeInput {
      .el-input {
        width: 220px;
        margin-right: 10px;
      }
    }
    // .getCode{
    //     color: #009588;
    //     background-color: #DEF7F3!important;
    //     border-color: #009588;
    // }
    // .getCode:hover{
    //     color: #fff;
    //     background-color: #009588!important;
    // }
  }
  .btnBox {
    text-align: center;
  }
  .mainCon {
    top: 198px;
    // background-color: #fff;
    // padding: 24px 24px 24px 0px;
    // .el-button--primary{
    //     background-color: #009588;
    //     border-color: #009588;
    // }
    .updateItem {
      width: 108px;
      height: 36px;
      text-align: center;
      color: #fff;
      font: bold 14px/36px Microsoft YaHei;
      background-color: #02a2aa;
    }
    .backYellow {
      background-color: #f9a243;
    }
    .itemBox {
      padding-left: 24px;
      margin-top: 20px;
      .itemValue {
        color: #222;
      }
    }
    .iconfont {
      margin-right: 10px;
    }
  }
}
</style>
